package com.lee.demo.widget;

import android.app.Activity;
import android.view.View;

import androidx.annotation.NonNull;

import com.lee.demo.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cn.lee.cplibrary.picker.calendarpicker.CalendarPicker;

/**
 * Created by ChrisLee on 2021/7/28.
 */
public class MyCalendarPicker extends CalendarPicker {
    private boolean isClear=true;//是否是清空状态，清空状态清空之前选择的日期缓存

    public MyCalendarPicker(Activity activity) {
        super(activity);
        tvDateSelect.setVisibility(View.GONE);//原本可见的选择的日期
        setRangeDateOnFuture(6);//选择未来6个月
        setIntervalNotes("开始", "结束");
        reset();
    }


//    @Override
//    protected boolean enableMaskView() {
//        //取消弹窗遮罩效果，通过自定义遮罩层视图解决自带弹窗遮罩致使系统导航栏亮度突兀问题
//        return true;
//    }

    @Override
    public void onDoubleSelect(@NonNull Date before, @NonNull Date after) {
        super.onDoubleSelect(before, after);
        titleView.setText(formatDate(startDate) + " — " + formatDate(endDate));//标题
        int day = daydiff(startDate, endDate);
        setSureTxt("确定" + (day + 1) + "晚");
        cancelView.setText("清空");
    }


    public void setSureTxt(String txt) {
        if ("确定".equals(txt)) {
            tvSure.setEnabled(false);
            tvSure.setBackgroundResource(R.drawable.cp_radius_toast);
            tvSure.setText(txt);
            isClear=true;
        } else {
            tvSure.setEnabled(true);
            tvSure.setBackgroundResource(R.drawable.cp_calendar_btn);
            tvSure.setText(txt);
            isClear=false;
        }
    }



    @Override
    protected void initData() {
        super.initData();
        if (isClear &&calendarAdapter!=null) {//
            calendarAdapter.select((Date) null, null);
        }
    }

    @Override
    protected void onCancel() {//点击
        calendarAdapter.select((Date) null, null);
        reset();

    }

    /**
     * 格式化时间：
     */
    public String formatDate(Date date) {
        String format = "M月d日";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    public static int daydiff(Date fDate, Date oDate) {
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(fDate);
        int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
        aCalendar.setTime(oDate);
        int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
        return day2 - day1;
    }

    private void reset() {
        titleView.setText("选择日期");//标题
        setSureTxt("确定");//确定按钮
        cancelView.setText("");
    }
}